package com.sky.ok.okex.websocket.base;

import com.sky.ok.okex.websocket.client.WebSocketService;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.sky.ok.okex.common.OKV3Const.*;

public abstract class WebSocketBase {

    private static final Logger log = LoggerFactory.getLogger("WebSocketBase.class");
    private WebSocketService service = null;
    private Request request = null;
    private OkHttpClient client = null;
    private WebSocketListenerV3 listener = new WebSocketListenerV3();
    private String url = null;
    private WebSocket webSocket;
    private Set<String> subscribChannel = new HashSet<String>();

    public WebSocketBase(String url, WebSocketService serivce) {
        this.url = url;
        this.service = serivce;
    }

    public void start() {
        if (url == null) {
            log.info("WebSocketClient start error  url can not be null");
            return;
        }
        if (service == null) {
            log.info("WebSocketClient start error  WebSocketService can not be null");
            return;
        }
        if (USE_PROXY == true) {
            log.info("使用" + PROXY_HOST + ":" + PROXY_PORT + "代理进行websocket链接");
            Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(PROXY_HOST, PROXY_PORT));
            client = new OkHttpClient().newBuilder()
                    //设置连接超时时间
                    .connectTimeout(50, TimeUnit.SECONDS)
                    //读取超时
                    .readTimeout(50, TimeUnit.SECONDS)
                    .proxy(proxy)
                    // 解决内存溢出问题
                    .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS)).build();
        } else {
            log.info("未使用代理进行websocket链接");
            client = new OkHttpClient().newBuilder()
                    //设置连接超时时间
                    .connectTimeout(50, TimeUnit.SECONDS)
                    //读取超时
                    .readTimeout(50, TimeUnit.SECONDS)
                    // 解决内存溢出问题
                    .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS)).build();
        }


        request = new Request.Builder()
                .url(WEBSOCKET_ADRESS_V3)
                .build();
        listener.setService(service);
        webSocket = client.newWebSocket(request, listener);
    }

    /*
     *
     * 传入需要订阅的频道信息
     * @author sky
     * @date 2019/1/30 16:33
     * @param [channel]
     * @return void
     */
    public void addChannel(String channel) {
        if (channel == null) {
            return;
        }
        //	String dataMsg = "{'event':'addChannel','channel':'" + channel + "'}";
        String dataMsg = "{\"op\": \"subscribe\", \"args\": \"" + channel + "\"}";
        log.debug("订阅:" + dataMsg);
        webSocket.send(dataMsg);
        subscribChannel.add(channel);

    }

    //取消订阅
    public void removeChannel(String channel) {
        if (channel == null) {
            return;
        }
        String dataMsg = "{\"op\": \"unsubscribe\", \"args\": " + channel + "}";
        log.debug("取消订阅:" + dataMsg);
        webSocket.send(dataMsg);
        subscribChannel.remove(channel);
    }

    public Set<String> getSubscribChannel() {
        return subscribChannel;
    }

    public void setSubscribChannel(Set<String> subscribChannel) {
        this.subscribChannel = subscribChannel;
    }

 /*   ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
    Task1 t1 = new Task1();
    //立即执行t1，3s后任务结束，再等待5s（间隔时间-消耗时间），如果有空余线程时，再次执行该任务
   pool.scheduleAtFixedRate(t1, 0, 5, TimeUnit.SECONDS);
*/


}



